import React, { useState } from "react";
import { Layout, Menu, Table, Form, Input, Select, Button, DatePicker, Modal } from "antd";
import { HomeOutlined, FileOutlined } from "@ant-design/icons";

const { Sider, Content } = Layout;

// 从 localStorage 中获取数据
const getInitialDataSource = () => {
  const storedData = localStorage.getItem('dataSource');
  return storedData? JSON.parse(storedData) : [
    {
      index: 1,
      id: 1,
      deviceName: "1号闸门",
      deviceType: "闸泵站",
      project: "闸1",
      abnormalType: "电压不足",
      status: "待处理",
      completeTime: "--",
      recorder: "--"
    },
    {
      index: 2,
      id: 2,
      deviceName: "闸2视频监控点1",
      deviceType: "视屏监控",
      project: "闸2",
      abnormalType: "设备掉线",
      status: "待审核",
      completeTime: "2022-10-10 15:00",
      recorder: "小天"
    },
    {
      index: 3,
      id: 3,
      deviceName: "水位站1",
      deviceType: "水雨情",
      project: "水位站",
      abnormalType: "无监测数据值",
      status: "已完成",
      completeTime: "2022-10-10 15:00",
      recorder: "小天"
    }
  ];
};

const Gongdan = () => {
  const [form] = Form.useForm();
  const [searchParams, setSearchParams] = useState({});
  const [collapsed, setCollapsed] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  // 新增一个状态存储所有数据
  const [allDataSource, setAllDataSource] = useState(getInitialDataSource()); 
  const [newDataSource, setNewDataSource] = useState(getInitialDataSource());
  const [isViewModalVisible, setIsViewModalVisible] = useState(false);
  const [viewRecord, setViewRecord] = useState(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);

  const columns = [
    {
      title: "序号",
      dataIndex: "index",
      width: 60,
      align: "center",
      render: (text, record) => record.index
    },
    {
      title: "设备名称",
      dataIndex: "deviceName",
      width: 120
    },
    {
      title: "设备类型",
      dataIndex: "deviceType",
      width: 120
    },
    {
      title: "所属工程",
      dataIndex: "project",
      width: 100
    },
    {
      title: "异常类型",
      dataIndex: "abnormalType",
      width: 120
    },
    {
      title: "状态",
      dataIndex: "status",
      width: 80,
      render: (text) => {
        if (text === "待处理") {
          return <span style={{ color: "orange" }}>{text}</span>;
        } else if (text === "待审核") {
          return <span style={{ color: "red" }}>{text}</span>;
        } else if (text === "已完成") {
          return <span style={{ color: "green" }}>{text}</span>;
        }
        return text;
      }
    },
    {
      title: "完成时间",
      dataIndex: "completeTime",
      width: 150
    },
    {
      title: "记录人员",
      dataIndex: "recorder",
      width: 100
    },
    {
      title: "操作",
      dataIndex: "operation",
      width: 100,
      align: "center",
      render: (_, record) => (
        <span key={`operation-${record.index}`}>
          {record.status === "待处理" && (
            <>
              <a href="#" style={{ color: "blue" }} onClick={() => {
                setViewRecord(record);
                setIsViewModalVisible(true);
              }}>查看</a> |{" "}
              <a href="/service/layout/gongdan/chuli" style={{ color: "blue" }}>处理</a> {" "}
              <Button type="danger" onClick={() => handleDelete(record.id)}>删除</Button> {/* 单条数据删除按钮 */}
            </>
          )}
          {record.status === "待审核" && (
            <>
              <a href="#" style={{ color: "blue" }} onClick={() => {
                setViewRecord(record);
                setIsViewModalVisible(true);
              }}>查看</a> |{" "}
              <a href="/service/layout/gongdan/shenhe" style={{ color: "blue" }}>审核</a> {" "}
              <Button type="danger" onClick={() => handleDelete(record.id)}>删除</Button> {/* 单条数据删除按钮 */}
            </>
          )}
          {record.status === "已完成" && (
            <a href="#" style={{ color: "blue" }} onClick={() => {
              setViewRecord(record);
              setIsViewModalVisible(true);
            }}>查看</a>
          )}
        </span>
      )
    }
  ];

  const handleSearch = () => {
    form.validateFields().then((values) => {
      console.log('表单获取的值:', values);
      const { endTime, startTime, projectName, status } = values;
      let filteredData = allDataSource; // 使用allDataSource进行过滤
      if (projectName) {
        filteredData = filteredData.filter(record => record.project === projectName);
      }
      if (status) {
        filteredData = filteredData.filter(record => record.status === status);
      }
      setSearchParams(values);
      setAllDataSource(filteredData); // 更新所有数据状态
      setCurrentPage(1); // 搜索后重置为第一页
      const page = 1; 
      const pageSize = 6; 
      const startIndex = (page - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      const paginatedData = filteredData.slice(startIndex, endIndex);
      setNewDataSource(paginatedData);
    });
  };

  const handleReset = () => {
    form.resetFields();
    setSearchParams({});
    const initialData = getInitialDataSource();
    setAllDataSource(initialData);
    setNewDataSource(initialData);
    setCurrentPage(1); // 重置后回到第一页
  };

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = () => {
    form.validateFields().then((values) => {
      const newIndex = allDataSource.length + 1;
      const newId = newIndex;
      const newItem = {
        index: newIndex,
        id: newId,
        deviceName: values.deviceName,
        deviceType: values.deviceType,
        project: values.project,
        abnormalType: values.abnormalType,
        status: values.status,
        completeTime: values.completeTime? values.completeTime.format('YYYY-MM-DD HH:mm') : '--',
        recorder: values.recorder
      };
      const updatedAllDataSource = [...allDataSource, newItem];
      setAllDataSource(updatedAllDataSource);
      setCurrentPage(1); // 添加后回到第一页
      const page = 1; 
      const pageSize = 6; 
      const startIndex = (page - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      const paginatedData = updatedAllDataSource.slice(startIndex, endIndex);
      setNewDataSource(paginatedData);
      localStorage.setItem('dataSource', JSON.stringify(updatedAllDataSource));
      form.resetFields();
      setIsModalVisible(false);
    });
  };

  const handleCancel = () => {
    form.resetFields();
    setIsModalVisible(false);
  };

  const handleViewCancel = () => {
    setIsViewModalVisible(false);
  };

  const handleDelete = (id) => {
    const updatedAllDataSource = allDataSource.filter(record => record.id!== id);
    setAllDataSource(updatedAllDataSource);
    setCurrentPage(1); // 删除后回到第一页
    const page = 1; 
    const pageSize = 6; 
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedData = updatedAllDataSource.slice(startIndex, endIndex);
    setNewDataSource(paginatedData);
    localStorage.setItem('dataSource', JSON.stringify(updatedAllDataSource));
  };

  const handleSelectChange = (newSelectedRowKeys) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const handleDeleteSelected = () => {
    const updatedAllDataSource = allDataSource.filter(record =>!selectedRowKeys.includes(record.id));
    setAllDataSource(updatedAllDataSource);
    setCurrentPage(1); // 全选删除后回到第一页
    const page = 1; 
    const pageSize = 6; 
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedData = updatedAllDataSource.slice(startIndex, endIndex);
    setNewDataSource(paginatedData);
    localStorage.setItem('dataSource', JSON.stringify(updatedAllDataSource));
    setSelectedRowKeys([]);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: handleSelectChange,
    getCheckboxProps: (record) => ({
      disabled: record.status === '已完成'
    })
  };

  return (
    <Layout>
      <Layout>
        <Content style={{ padding: "24px", overflow: "auto" }}>
          <Form form={form} layout="inline">
            <Form.Item name="endTime" label="结束时间">
              <DatePicker placeholder="Select date" />
            </Form.Item>
            <Form.Item name="startTime" label="开始时间">
              <DatePicker placeholder="Select date" />
            </Form.Item>
            <Form.Item name="projectName" label="工程名称">
              <Select placeholder="请选择">
                <Select.Option value="闸1">闸1</Select.Option>
                <Select.Option value="闸2">闸2</Select.Option>
                <Select.Option value="水位站">水位站</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item name="status" label="状态">
              <Select placeholder="请选择">
                <Select.Option value="待处理">待处理</Select.Option>
                <Select.Option value="待审核">待审核</Select.Option>
                <Select.Option value="已完成">已完成</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item>
              <Button type="primary" onClick={handleSearch}>
                查询
              </Button>
              <Button onClick={handleReset}>重置</Button>
              <Button type="primary" onClick={showModal} style={{ marginLeft: 8 }}>
                添加
              </Button>
              <Button type="danger" onClick={handleDeleteSelected} disabled={selectedRowKeys.length === 0}>
                批量删除
              </Button> {/* 修改按钮文字为批量删除 */}
            </Form.Item>
          </Form>
          <Table
            columns={columns}
            dataSource={newDataSource}
            rowKey="id"
            rowSelection={rowSelection}
            pagination={{
              current: currentPage,
              pageSize: 6,
              total: allDataSource.length,
              onChange: (page, pageSize) => {
                setCurrentPage(page);
                const startIndex = (page - 1) * pageSize;
                const endIndex = startIndex + pageSize;
                const paginatedData = allDataSource.slice(startIndex, endIndex);
                setNewDataSource(paginatedData);
              }
            }}
          />
          <Modal title="添加数据" open={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
            <Form form={form} layout="vertical">
              <Form.Item name="deviceName" label="设备名称" rules={[{ required: true, message: '请输入设备名称' }]}>
                <Input />
              </Form.Item>
              <Form.Item name="deviceType" label="设备类型" rules={[{ required: true, message: '请输入设备类型' }]}>
                <Input />
              </Form.Item>
              <Form.Item name="project" label="所属工程" rules={[{ required: true, message: '请选择所属工程' }]}>
                <Select placeholder="请选择">
                  <Select.Option value="闸1">闸1</Select.Option>
                  <Select.Option value="闸2">闸2</Select.Option>
                  <Select.Option value="水位站">水位站</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item name="abnormalType" label="异常类型" rules={[{ required: true, message: '请输入异常类型' }]}>
                <Input />
              </Form.Item>
              <Form.Item name="status" label="状态" rules={[{ required: true, message: '请选择状态' }]}>
                <Select placeholder="请选择">
                  <Select.Option value="待处理">待处理</Select.Option>
                  <Select.Option value="待审核">待审核</Select.Option>
                  <Select.Option value="已完成">已完成</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item name="completeTime" label="完成时间">
                <DatePicker showTime placeholder="Select date and time" />
              </Form.Item>
              <Form.Item name="recorder" label="记录人员" rules={[{ required: true, message: '请输入记录人员' }]}>
                <Input />
              </Form.Item>
            </Form>
          </Modal>
          <Modal title="查看详情" open={isViewModalVisible} onCancel={handleViewCancel} footer={null}>
            {viewRecord && (
              <div>
                <p><strong>序号:</strong> {viewRecord.index}</p>
                <p><strong>设备名称:</strong> {viewRecord.deviceName}</p>
                <p><strong>设备类型:</strong> {viewRecord.deviceType}</p>
                <p><strong>所属工程:</strong> {viewRecord.project}</p>
                <p><strong>异常类型:</strong> {viewRecord.abnormalType}</p>
                <p><strong>状态:</strong> {viewRecord.status}</p>
                <p><strong>完成时间:</strong> {viewRecord.completeTime}</p>
                <p><strong>记录人员:</strong> {viewRecord.recorder}</p>
              </div>
            )}
          </Modal>
        </Content>
      </Layout>
    </Layout>
  );
};

export default Gongdan;